import React, { Suspense } from 'react'
import { Routes, Route, Navigate } from 'react-router-dom'
import Login from './pages/Login'
import NotFound from './pages/NotFound'
import routes from './routes'
import { isLogin } from './utils/cookieLogin'
import LayOut from './Layout'
import { Spin } from 'antd'
import { useSelector } from 'react-redux'

export default function App() {
  // 路由过滤 角色鉴权
  const role = useSelector(state => state.user.role)
  const authRole = routes.filter(route => {
    return route.roles === '*' || (route.roles.includes(role))
  })

  return (
    // 配合 routes  lazy  ----suspense和lazy
    <Suspense fallback={
      <div style={{
        width: '100%',
        height: '100%',
        position: 'fixed',
        top: '50%',
        left: '50%',
        // display: 'flex',
        // justifyContent: 'center',
        // alignItems: 'center'
      }}
      >
        <div className="content">
          <Spin tip="Loading" size="large">
          </Spin>
        </div>
      </div>
    }>
      <Routes>
        {/* 二级路由记得Outlet出口，
        layout中content引入Outlet、设置出口 */}


        {/* 判断 是否登录Cookie存在，没有就直接去登录页 */}

        {/* 过滤权限admin、角色权限鉴权 */}
        <Route path="/" element={
          isLogin()
            ?
            <LayOut />
            :
            <Navigate to={'/login'} />
        }>
          {
            authRole.map(route => {
              return (
                <Route
                  key={route.path}
                  path={route.path}
                  element={<route.component />}
                />
              )
            })
          }
          <Route path="/" element={<Navigate to="/dashBoard" />} />
        </Route>

        <Route path="/login" element={<Login />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </Suspense>
  )
}
